<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <CommonDateSearch ref="searchRef" @search="handleSearch"></CommonDateSearch>
    <div class="content-box">
      <!-- 第一排固定显示各分厂电量和各分厂用电费用 -->
      <div class="chart-box first-row" 
           v-if="electricityItem && electricityItem.loading !== undefined" 
           :key="electricityItem.dictCode">
        <Line :is="electricityItem.componentName" 
              :loading="electricityItem.loading" 
              :chartData="electricityItem.chartData" 
              :title="electricityItem.itemName" />
      </div>
      <div class="chart-box first-row" 
           v-if="costItem && costItem.loading !== undefined" 
           :key="costItem.dictCode">
        <Line :is="costItem.componentName" 
              :loading="costItem.loading" 
              :chartData="costItem.chartData" 
              :title="costItem.itemName" />
      </div>
      
      <!-- 其他图表 -->
      <div class="chart-box" 
           v-if="otherItems.length > 0" 
           v-for="item in otherItems" 
           :key="item.dictCode">
        <Line :is="item.componentName" 
              :loading="item.loading" 
              :chartData="item.chartData" 
              :title="item.itemName" />
      </div>
    </div>
  </PageWrapper>
</template>

<script setup>
import Line from '@/components/Charts/Line/index.vue'
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue'
import { PageWrapper } from '@/components/Page'
import CommonDateSearch from '@/components/CommonDateSearch/index.vue'
import { getEleChildData, getEleChildDatainfo } from '@/api/power/electricity/electricity.ts'
import { getDictListByCode } from '@/api/sys/dict'
import { cloneDeep } from 'lodash-es';

defineOptions({ name: 'BranchFactory' })

const searchInfo = reactive({})
const dictCode = 'branch_usage'
const lineTypeList = ref([])
const dataReady = ref(false)
const searchRef = ref()
const infoList = ref()
const infoxaxisList = ref()

// 计算属性：提取各分厂电量和各分厂用电费用项
const electricityItem = computed(() => 
  lineTypeList.value.find(item => item.itemName === '各分厂电量')
)

const costItem = computed(() => 
  lineTypeList.value.find(item => item.itemName === '各分厂用电费用')
)

// 计算属性：其他图表项
const otherItems = computed(() => 
  lineTypeList.value.filter(item => 
    item.itemName !== '各分厂电量' && item.itemName !== '各分厂用电费用'
  )
)

onMounted(async () => {
  await getTypeList()
  searchRef.value.handleSearch()
})

const getTypeList = async () => {
  const res = await getDictListByCode(dictCode)
  dataReady.value = true
  lineTypeList.value = res.map((item) => ({
    ...item,
    loading: true,
    chartData: {},
  }))
}

const handleSearch = async (params) => {
  if (dataReady.value) {
    Object.assign(searchInfo, params)
    await getLineChartData(params)
  } else {
    setTimeout(() => {
      handleSearch(params)
    }, 200)
  }
}

const getLineChartData = async (searchInfo) => {
  try {
    // 先获取各分厂电量数据
    const electricityItem = lineTypeList.value.find(item => item.itemName === '各分厂电量')
    if (electricityItem) {
      electricityItem.loading = true

      const res = await getEleChildDatainfo({
        ...searchInfo,
        dictCode,
        itemName: electricityItem.itemName,
      })

      // 更新各分厂电量数据
      electricityItem.chartData = res
      infoList.value = res.codeyAxisList
      infoxaxisList.value = res.xaxisList
      electricityItem.loading = false
    }

    // 处理各分厂用电费用数据
    const costItem = lineTypeList.value.find(item => item.itemName === '各分厂用电费用')
    if (costItem) {
      costItem.loading = true
      
      try {
        // 确保依赖数据已准备好
        if (!infoList.value || !infoxaxisList.value) {
          console.error('各分厂用电费用数据依赖未准备好')
        } else {
          // 使用各分厂电量的x轴和y轴数据
          costItem.chartData = {
            ...costItem.chartData,
            yaxisList: cloneDeep(infoList.value),
            xaxisList: cloneDeep(infoxaxisList.value),
          }
        }
      } catch (error) {
        console.error(`获取${costItem.itemName}数据失败:`, error)
      } finally {
        costItem.loading = false
      }
    }

    // 处理其他图表数据
    for (const item of otherItems.value) {
      item.loading = true

      try {
        const res = await getEleChildData({
          ...searchInfo,
          dictCode,
          itemName: item.itemName,
        })

        // 更新图表数据
        item.chartData = res
      } catch (error) {
        console.error(`获取${item.itemName}数据失败:`, error)
      } finally {
        item.loading = false
      }
    }
  } catch (error) {
    console.error('获取图表数据失败:', error)
    // 确保所有图表加载状态都被设置为false
    lineTypeList.value.forEach(item => {
      item.loading = false
    })
  }
}
</script>

<style scoped lang="scss">
.content-box {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
  padding: 4px;
  overflow: auto;
  background: #fff;

  .chart-box {
    flex-shrink: 0;
    width: calc(100% / 2);
    height: 50%;
    min-height: 240px;
    padding: 4px;
    
    // 确保第一排图表总是在顶部
    &.first-row {
      order: -1;
    }
  }
}
</style>